package com.ls.pattern.proxy.dynamicproxy;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * CgLib动态代理实现
 *
 * @author 挥之以墨
 */
public class CgLibMeipo implements MethodInterceptor {

    @SuppressWarnings("unchecked")
    public <T> T getInstance(Class<T> target) {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(target);
        enhancer.setCallback(this);
        return (T) enhancer.create();
    }

    @Override
    public Object intercept(Object o, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
        before();
        Object obj = methodProxy.invokeSuper(o, args);
        after();
        return obj;
    }

    private void before() {
        System.out.println("有什么要求？");
    }

    private void after() {
        System.out.println("已经找到符合条件的妹纸");
    }
}
